import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oli/pages/login/state.dart';
import 'package:oli/widget/RandomShapesPainter.dart';

import 'logic.dart';

class LoginPage extends StatelessWidget {
  const LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.find<LoginLogic>();
    final state = logic.state;
    logic.getCode();
    return Scaffold(
      body: Stack(
        children: [
          Obx(
            () => CustomPaint(
              painter: RandomShapesPainter(state.shapes.value),
              child: Container(),
            ),
          ),
          // 顶部的登录/注册切换文本
          Positioned(
            top: 50,
            left: 0,
            right: 0,
            child: _buildLoginRegisterToggle(logic, state),
          ),
          // 根据状态显示登录或注册内容区域
          Positioned(
            top: 120,
            left: 20,
            right: 20,
            child: Obx(
              () => SingleChildScrollView(
                child:
                    state.isLogin.value
                        ? _buildLoginSection(logic, state)
                        : _buildRegisterSectio(logic, state),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建登录/注册切换按钮
  Widget _buildLoginRegisterToggle(LoginLogic logic, LoginState state) {
    return Center(
      child: GestureDetector(
        onTap: () => logic.toggleLoginRegister(),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Obx(
            () => Text(
              "切换: ${state.isLogin.value ? '注册' : '登录'}",
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 构建登录部分的UI
  Widget _buildLoginSection(LoginLogic logic, LoginState state) {
    return _buildFormContainer(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildWelcomeRow("欢迎回来，", "朋友"),
          const SizedBox(height: 20),
          _buildTextField("电子邮箱地址", state.emailLoginController.value),
          const SizedBox(height: 20),
          _buildPasswordField(state.passwordLoginController.value),
          const SizedBox(height: 10),
          _buildCaptchaComponent(logic, state),
          const SizedBox(height: 10),
          Align(
            alignment: Alignment.centerRight,
            child: TextButton(
              onPressed: null,
              child: const Text("找回密码", style: TextStyle(color: Colors.blue)),
            ),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            // 提供一个非 null 的回调函数，使按钮可点击
            onPressed: () {
              print('登录按钮被点击');
              logic.reg();
            },

            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              padding: const EdgeInsets.symmetric(vertical: 15),
            ),
            child: const Center(
              child: Text("登录 →", style: TextStyle(fontSize: 18)),
            ),
          ),
        ],
      ),
    );
  }

  // 构建注册部分的UI
  Widget _buildRegisterSectio(LoginLogic logic, LoginState state) {
    return _buildFormContainer(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildWelcomeRow("你好，新用户", ""),
          const SizedBox(height: 10),
          const Text("让我们开始创建账户", style: TextStyle(fontSize: 16)),
          const SizedBox(height: 20),
          _buildTextField("姓名", state.nameRegisterController.value),
          const SizedBox(height: 20),
          _buildTextField("电子邮箱地址", state.emailRegisterController.value),
          const SizedBox(height: 20),
          _buildPasswordField(state.passwordRegisterController.value),
          const SizedBox(height: 10),
          _buildCaptchaComponent(logic, state),
          const SizedBox(height: 10),
          Align(
            alignment: Alignment.centerRight,
            child: TextButton(
              onPressed: null,
              child: const Text("找回密码", style: TextStyle(color: Colors.blue)),
            ),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            // 提供一个非 null 的回调函数，使按钮可点击
            onPressed: () {
              print('注册按钮被点击');
              logic.login();
            },
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              padding: const EdgeInsets.symmetric(vertical: 15),
            ),
            child: const Center(
              child: Text("注册 →", style: TextStyle(fontSize: 18)),
            ),
          ),
        ],
      ),
    );
  }

  // 构建带有毛玻璃效果的表单容器
  Widget _buildFormContainer({required Widget child}) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(20),
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.2),
            borderRadius: BorderRadius.circular(20),
          ),
          padding: const EdgeInsets.all(20),
          child: child,
        ),
      ),
    );
  }

  // 构建欢迎信息行
  Widget _buildWelcomeRow(String greeting, String name) {
    return Row(
      children: [
        const CircleAvatar(child: Icon(Icons.person)),
        const SizedBox(width: 10),
        Text(
          greeting,
          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
        ),
        if (name.isNotEmpty)
          Text(
            name,
            style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
          ),
      ],
    );
  }

  // 构建普通文本输入框
  Widget _buildTextField(String label, TextEditingController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 5),
        TextField(
          controller: controller,
          decoration: InputDecoration(
            hintText: "请输入$label",
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
          ),
        ),
      ],
    );
  }

  // 构建密码输入框
  Widget _buildPasswordField(TextEditingController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          "密码",
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 5),
        TextField(
          obscureText: true,
          controller: controller,
          decoration: InputDecoration(
            hintText: "8位以上字符",
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            suffixIcon: IconButton(
              icon: const Icon(Icons.visibility),
              onPressed: null,
            ),
          ),
        ),
      ],
    );
  }

  // 在 _LoginRegPageState 类中添加以下方法
  Widget _buildCaptchaComponent(LoginLogic logic, LoginState state) {
    return Row(
      children: [
        // 验证码图片
        Expanded(
          flex: 2,
          child: Image.network(
            state.captchaImageUrl.value,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return const Center(child: Text('加载验证码图片失败'));
            },
          ),
        ),
        const SizedBox(width: 10),
        // 验证码输入框
        Expanded(
          flex: 3,
          child: _buildTextField("验证码", state.captchaController),
        ),
      ],
    );
  }
}
